package com.wk.springboot.config;

import java.util.ArrayList;
import java.util.List;
import org.springframework.batch.core.Step;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Classname ItemProcessorConfig
 * @Description ItemProcessor的配置
 * @Date 2020/4/7 11:22
 * @Author by weikai
 */
@Configuration
public class ItemProcessorConfig {

  /**
   * 有这种场景，读取的资源数据需要转换两次才能写入到数据库
   * 只需要在step的processor()方法中用这个compositeProcessor即可
   */
  @Bean
  public CompositeItemProcessor compositeProcessor() {
    List<ItemProcessor> delegates = new ArrayList<>(2);
    delegates.add(new FooProcessor());
    delegates.add(new BarProcessor());

    CompositeItemProcessor processor = new CompositeItemProcessor();
    processor.setDelegates(delegates);
    return processor;
  }


  /**
   * 这些都是item转换所需要的类
   */
  class Foo {

  }

  class Bar {

    Bar(Foo foo) {
    }
  }

  class Foobar {

    Foobar(Bar bar) {
    }
  }

  public class FooProcessor implements ItemProcessor<Foo, Bar> {

    @Override
    public Bar process(Foo foo) throws Exception {
      //Perform simple transformation, convert a Foo to a Bar
      return new Bar(foo);
    }
  }

  public class BarProcessor implements ItemProcessor<Bar, Foobar> {

    @Override
    public Foobar process(Bar bar) throws Exception {
      return new Foobar(bar);
    }
  }

  public class FoobarWriter implements ItemWriter<Foobar> {

    @Override
    public void write(List<? extends Foobar> items) throws Exception {
      //write items
    }
  }
}
